package pt.nmfa.peste.scrappers.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public abstract class FileScrapper {
	
	protected String fileContent;
	protected String file;
	
	
	public String getFileContent() {
		return fileContent;
	}

	public String getFile() {
		return file;
	}

	protected FileScrapper() {
		super();
	}
	
	public FileScrapper(String file) {
		super();
		this.file=file;
		loadFile(file);
		update();
	}
	
	protected abstract void update();
	
	protected boolean contains(String string)
	{
		return fileContent.contains(string);
	}
	

	
	protected String getValueAsString(String patternStr)
	{
		return getValueAsString(patternStr,fileContent,Pattern.MULTILINE);
	}
	
	protected int getValueAsInt (String patternStr,String source)
	{
		return Integer.parseInt(getValueAsString(patternStr,source,Pattern.MULTILINE));
	}
	
	public List<String> getValueAsList(String patternStr)
	{
		ArrayList<String> list=new ArrayList<String>();
		Pattern pattern = Pattern.compile(patternStr,Pattern.MULTILINE);
		
		Matcher matcher=pattern.matcher(fileContent);
		while(matcher.find())
		{
			list.add(matcher.group(1).trim());
		}
		return list;
	}
	
	protected String getValueAsString(String patternStr,String source,int flags)
	{
		Pattern pattern = Pattern.compile(patternStr,flags);
		
		Matcher matcher=pattern.matcher(source);
		if(matcher.find())
		{
			return matcher.group(1).trim();
		}
		return null;
	}
	
	protected int getValueAsInt (String patternStr)
	{
		return Integer.parseInt(getValueAsString(patternStr));
	}
	
	protected double getValueAsDouble (String patternStr)
	{
		return Double.parseDouble(getValueAsString(patternStr));
	}
	
	protected void loadFile(String file)
	{
		 BufferedReader in =null;
		 StringBuffer sb=new StringBuffer();
		try {
		     in = new BufferedReader(new FileReader(file));
		    String str;
		    while ((str = in.readLine()) != null) {
		    	str = str.replaceAll("\\t"," ");
		    	sb.append(str);
		    }
		    this.fileContent= sb.toString();
		    
		} catch (IOException e) {
			e.printStackTrace();			
		} finally{
			if(in!=null)
				try {
					in.close();
				} catch (IOException e) {
				}
		};
		
	}
	
	
}
